<template>
  <div class="settings">
    <div class="page-header">
      <h2>系统设置</h2>
    </div>

    <el-tabs v-model="activeTab">
      <el-tab-pane label="基本设置" name="basic">
        <el-form
          ref="basicFormRef"
          :model="basicForm"
          :rules="basicRules"
          label-width="120px"
          class="settings-form"
        >
          <el-form-item label="系统名称" prop="system_name">
            <el-input v-model="basicForm.system_name" />
          </el-form-item>
          <el-form-item label="API地址" prop="api_url">
            <el-input v-model="basicForm.api_url" />
          </el-form-item>
          <el-form-item label="日志级别" prop="log_level">
            <el-select v-model="basicForm.log_level" style="width: 200px">
              <el-option label="DEBUG" value="debug" />
              <el-option label="INFO" value="info" />
              <el-option label="WARNING" value="warning" />
              <el-option label="ERROR" value="error" />
            </el-select>
          </el-form-item>
          <el-form-item label="自动备份">
            <el-switch v-model="basicForm.auto_backup" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleBasicSubmit">保存设置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="通知设置" name="notification">
        <el-form
          ref="notificationFormRef"
          :model="notificationForm"
          :rules="notificationRules"
          label-width="120px"
          class="settings-form"
        >
          <el-form-item label="邮件通知">
            <el-switch v-model="notificationForm.email_enabled" />
          </el-form-item>
          <template v-if="notificationForm.email_enabled">
            <el-form-item label="SMTP服务器" prop="smtp_server">
              <el-input v-model="notificationForm.smtp_server" />
            </el-form-item>
            <el-form-item label="SMTP端口" prop="smtp_port">
              <el-input-number v-model="notificationForm.smtp_port" :min="1" :max="65535" />
            </el-form-item>
            <el-form-item label="发件人邮箱" prop="sender_email">
              <el-input v-model="notificationForm.sender_email" />
            </el-form-item>
            <el-form-item label="邮箱密码" prop="email_password">
              <el-input v-model="notificationForm.email_password" type="password" show-password />
            </el-form-item>
          </template>
          <el-form-item>
            <el-button type="primary" @click="handleNotificationSubmit">保存设置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="安全设置" name="security">
        <el-form
          ref="securityFormRef"
          :model="securityForm"
          :rules="securityRules"
          label-width="120px"
          class="settings-form"
        >
          <el-form-item label="密码有效期(天)" prop="password_expire_days">
            <el-input-number 
              v-model="securityForm.password_expire_days"
              :min="0"
              :max="365"
            />
          </el-form-item>
          <el-form-item label="登录失败锁定">
            <el-switch v-model="securityForm.login_lock_enabled" />
          </el-form-item>
          <template v-if="securityForm.login_lock_enabled">
            <el-form-item label="失败次数" prop="max_login_attempts">
              <el-input-number
                v-model="securityForm.max_login_attempts"
                :min="1"
                :max="10"
              />
            </el-form-item>
            <el-form-item label="锁定时间(分钟)" prop="lock_duration">
              <el-input-number
                v-model="securityForm.lock_duration"
                :min="1"
                :max="1440"
              />
            </el-form-item>
          </template>
          <el-form-item>
            <el-button type="primary" @click="handleSecuritySubmit">保存设置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const activeTab = ref('basic')

// 基本设置
const basicFormRef = ref(null)
const basicForm = reactive({
  system_name: 'TWRPA 智能RPA系统',
  api_url: 'http://localhost:8000',
  log_level: 'info',
  auto_backup: true
})

const basicRules = {
  system_name: [
    { required: true, message: '请输入系统名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  api_url: [
    { required: true, message: '请输入API地址', trigger: 'blur' },
    { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
  ]
}

// 通知设置
const notificationFormRef = ref(null)
const notificationForm = reactive({
  email_enabled: false,
  smtp_server: '',
  smtp_port: 587,
  sender_email: '',
  email_password: ''
})

const notificationRules = {
  smtp_server: [
    { required: true, message: '请输入SMTP服务器地址', trigger: 'blur' }
  ],
  sender_email: [
    { required: true, message: '请输入发件人邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  email_password: [
    { required: true, message: '请输入邮箱密码', trigger: 'blur' }
  ]
}

// 安全设置
const securityFormRef = ref(null)
const securityForm = reactive({
  password_expire_days: 90,
  login_lock_enabled: true,
  max_login_attempts: 5,
  lock_duration: 30
})

const securityRules = {
  password_expire_days: [
    { required: true, message: '请输入密码有效期', trigger: 'blur' }
  ],
  max_login_attempts: [
    { required: true, message: '请输入最大登录失败次数', trigger: 'blur' }
  ],
  lock_duration: [
    { required: true, message: '请输入锁定时间', trigger: 'blur' }
  ]
}

// API调用
const fetchSettings = async () => {
  try {
    const response = await fetch('http://localhost:8000/api/settings', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    if (!response.ok) {
      throw new Error('获取设置失败')
    }
    const data = await response.json()
    
    // 更新表单数据
    Object.assign(basicForm, {
      system_name: data.system_name,
      api_url: data.api_url,
      log_level: data.log_level,
      auto_backup: data.auto_backup
    })

    Object.assign(notificationForm, {
      email_enabled: data.email_enabled,
      smtp_server: data.smtp_server,
      smtp_port: data.smtp_port,
      sender_email: data.sender_email
    })

    Object.assign(securityForm, {
      password_expire_days: data.password_expire_days,
      login_lock_enabled: data.login_lock_enabled,
      max_login_attempts: data.max_login_attempts,
      lock_duration: data.lock_duration
    })
  } catch (error) {
    console.error('获取设置失败:', error)
    ElMessage.error('获取设置失败')
  }
}

// 提交处理
const handleBasicSubmit = async () => {
  if (!basicFormRef.value) return
  
  try {
    await basicFormRef.value.validate()
    const response = await fetch('http://localhost:8000/api/settings/basic', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(basicForm)
    })

    if (!response.ok) {
      throw new Error('保存设置失败')
    }

    ElMessage.success('基本设置保存成功')
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error(error.message || '保存设置失败')
  }
}

const handleNotificationSubmit = async () => {
  if (!notificationFormRef.value) return
  
  try {
    await notificationFormRef.value.validate()
    const response = await fetch('http://localhost:8000/api/settings/notification', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(notificationForm)
    })

    if (!response.ok) {
      throw new Error('保存设置失败')
    }

    ElMessage.success('通知设置保存成功')
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error(error.message || '保存设置失败')
  }
}

const handleSecuritySubmit = async () => {
  if (!securityFormRef.value) return
  
  try {
    await securityFormRef.value.validate()
    const response = await fetch('http://localhost:8000/api/settings/security', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(securityForm)
    })

    if (!response.ok) {
      throw new Error('保存设置失败')
    }

    ElMessage.success('安全设置保存成功')
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error(error.message || '保存设置失败')
  }
}

// 生命周期钩子
onMounted(async () => {
  await fetchSettings()
})
</script>

<style lang="scss" scoped>
.settings {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

  .page-header {
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }
  }

  .settings-form {
    max-width: 600px;
    margin-top: 20px;
  }
}
</style> 